import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart';
import 'package:flutter/foundation.dart';

///http基础管理
abstract class BaseHttp extends DioForNative {
  BaseHttp() {
    /// 初始化 加入app通用处理
    (transformer as DefaultTransformer).jsonDecodeCallback = parseJson;
    interceptors..add(HeaderInterceptor());
    init();
  }

  void init();
}

///可以设置超时 时间等
class HeaderInterceptor extends InterceptorsWrapper {
  @override
  Future onRequest(RequestOptions options) {
    options.connectTimeout = 10 * 1000;
    options.receiveTimeout = 10 * 1000;
    return super.onRequest(options);
  }
}

///返回结果的 超类，主要用于校验成功还是失败
abstract class BaseRespData {
  int code = -1;
  String message;
  dynamic data;
  bool success = false;

  BaseRespData({this.code, this.message, this.data});

  @override
  String toString() {
    return 'BaseRespData{code:$code,message:$message,data:$data}';
  }
}

///接口的code没有返回true的异常
class NotSuccessException implements Exception {
  int code;
  String message;

  NotSuccessException.fromRespData(BaseRespData respData) {
    code = respData.code;
    message = respData.message;
  }
}

///用于未登录或权限不够，需要授权操作
class UnAuthorizedException implements Exception {
  const UnAuthorizedException();
}

_parseAndDecode(String resp) {
  return jsonDecode(resp);
}

parseJson(String text) {
  return compute(_parseAndDecode, text);
}

